// 博客列表管理模块
class BlogListManager {
    constructor() {
        this.blogs = [];
        this.filteredBlogs = [];
        this.currentPage = 1;
        this.pageSize = 10;
        this.currentFilter = '';
        this.currentSearch = '';
        
        this.init();
    }

    init() {
        // 加载博客数据
        this.loadBlogs();
        
        // 绑定事件
        this.bindEvents();
    }

    // 绑定事件
    bindEvents() {
        // 搜索输入
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.currentSearch = e.target.value;
                this.filterAndDisplayBlogs();
            });
        }

        // 搜索按钮
        const searchBtn = document.getElementById('searchBtn');
        if (searchBtn) {
            searchBtn.addEventListener('click', () => {
                this.filterAndDisplayBlogs();
            });
        }
    }

    // 加载博客数据
    async loadBlogs() {
        try {
            // 从Blogs.json文件加载数据
            const response = await fetch('../../frontend/AiBlog/Blogs.json');
            if (response.ok) {
                const data = await response.json();
                this.blogs = data.blogs || [];
                this.filteredBlogs = [...this.blogs];
                console.log('从Blogs.json加载博客数据成功:', this.blogs.length);
                this.displayBlogs();
            } else {
                throw new Error(`文件加载失败: ${response.status}`);
            }
        } catch (error) {
            console.error('Error loading blogs:', error);
            this.showError('加载博客数据失败: ' + error.message);
        }
    }

    // 筛选和显示博客
    filterAndDisplayBlogs() {
        this.currentPage = 1;
        
        // 应用搜索筛选
        this.filteredBlogs = this.blogs.filter(blog => {
            const matchesSearch = !this.currentSearch || 
                blog.title.toLowerCase().includes(this.currentSearch.toLowerCase()) ||
                (blog.summary && blog.summary.toLowerCase().includes(this.currentSearch.toLowerCase())) ||
                (blog.category && blog.category.toLowerCase().includes(this.currentSearch.toLowerCase())) ||
                (blog.author && blog.author.toLowerCase().includes(this.currentSearch.toLowerCase())) ||
                (blog.tags && blog.tags.some(tag => tag.toLowerCase().includes(this.currentSearch.toLowerCase())));
            
            return matchesSearch;
        });

        this.displayBlogs();
    }

    // 显示博客列表
    displayBlogs() {
        const tableBody = document.getElementById('blogTableBody');
        if (!tableBody) return;

        if (this.filteredBlogs.length === 0) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="10" class="px-6 py-12 text-center text-gray-500">
                        <i class="fas fa-inbox text-4xl mb-3 opacity-50"></i>
                        <p>没有找到匹配的博客</p>
                    </td>
                </tr>
            `;
            this.updatePagination();
            return;
        }

        // 计算分页
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = Math.min(startIndex + this.pageSize, this.filteredBlogs.length);
        const pageBlogs = this.filteredBlogs.slice(startIndex, endIndex);

        // 生成表格行
        const rowsHTML = pageBlogs.map(blog => {
            const publishDate = blog.publishDate ? commonManager.formatDate(blog.publishDate) : '未设置';
            const tags = blog.tags ? blog.tags.join(', ') : '无标签';
            
            return `
                <tr class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 sticky-col sticky-left bg-white">${blog.id}</td>
                    <td class="px-6 py-4">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 h-10 w-10">
                                <div class="h-10 w-10 rounded-lg bg-gradient-to-r from-blue-500 to-purple-600 flex items-center justify-center">
                                    <i class="fas fa-file-alt text-white text-sm"></i>
                                </div>
                            </div>
                            <div class="ml-4">
                                <div class="text-sm font-medium text-gray-900">${blog.title}</div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 text-sm text-gray-500 max-w-xs">
                        <div class="truncate" title="${blog.summary || '暂无摘要'}">${blog.summary || '暂无摘要'}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${blog.contentFile || '未设置'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${blog.category || '未分类'}</td>
                    <td class="px-6 py-4 text-sm text-gray-500 max-w-xs">
                        <div class="truncate" title="${tags}">${tags}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${blog.author || '未知'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${blog.authorTitle || '未设置'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${publishDate}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium sticky-col sticky-right bg-white">
                        <div class="flex space-x-2">
                            <a href="../../frontend/AiBlog/blog-detail.html?id=${blog.id}" target="_blank" class="text-green-600 hover:text-green-900 transition-colors">
                                <i class="fa-solid fa-eye mr-1"></i>查看
                            </a>
                            <a href="edit.html?id=${blog.id}" class="text-blue-600 hover:text-blue-900 transition-colors">
                                <i class="fa-solid fa-pen-to-square mr-1"></i>编辑
                            </a>
                            <button onclick="blogListManager.deleteBlog('${blog.id}')" class="text-red-600 hover:text-red-900 transition-colors">
                                <i class="fa-solid fa-trash mr-1"></i>删除
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');

        tableBody.innerHTML = rowsHTML;
        this.updatePagination();
    }

    // 更新分页
    updatePagination() {
        const totalPages = Math.ceil(this.filteredBlogs.length / this.pageSize);
        const startIndex = (this.currentPage - 1) * this.pageSize + 1;
        const endIndex = Math.min(this.currentPage * this.pageSize, this.filteredBlogs.length);

        // 更新统计信息
        this.updateElement('startIndex', startIndex);
        this.updateElement('endIndex', endIndex);
        this.updateElement('totalCount', this.filteredBlogs.length);

        // 生成分页按钮
        const pagination = document.getElementById('pagination');
        if (pagination) {
            let paginationHTML = '';

            // 上一页
            if (this.currentPage > 1) {
                paginationHTML += `
                    <button onclick="blogListManager.goToPage(${this.currentPage - 1})" class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-l-lg hover:bg-gray-50">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                `;
            }

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === this.currentPage) {
                    paginationHTML += `
                        <button class="px-3 py-2 text-sm font-medium text-white bg-blue-600 border border-blue-600">
                            ${i}
                        </button>
                    `;
                } else {
                    paginationHTML += `
                        <button onclick="blogListManager.goToPage(${i})" class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 hover:bg-gray-50">
                            ${i}
                        </button>
                    `;
                }
            }

            // 下一页
            if (this.currentPage < totalPages) {
                paginationHTML += `
                    <button onclick="blogListManager.goToPage(${this.currentPage + 1})" class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-r-lg hover:bg-gray-50">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                `;
            }

            pagination.innerHTML = paginationHTML;
        }
    }

    // 跳转到指定页
    goToPage(page) {
        this.currentPage = page;
        this.displayBlogs();
    }

    // 删除博客
    async deleteBlog(blogId) {
        const confirmed = await commonManager.confirm(
            '确定要删除这篇博客吗？此操作不可恢复。',
            '确认删除'
        );

        if (!confirmed) return;

        try {
            // 从数组中移除
            this.blogs = this.blogs.filter(blog => blog.id !== parseInt(blogId));
            this.filteredBlogs = this.filteredBlogs.filter(blog => blog.id !== parseInt(blogId));

            // 更新显示
            this.displayBlogs();

            commonManager.showSuccess('博客删除成功');
        } catch (error) {
            console.error('Error deleting blog:', error);
            commonManager.showError(`删除博客失败: ${error.message}`);
        }
    }

    // 保存博客数据到文件
    async saveBlogsToFile() {
        try {
            // 这里可以实现保存到Blogs.json文件的逻辑
            // 目前只是从文件读取，删除操作只在内存中生效
            console.log('博客数据已更新，需要手动保存到Blogs.json文件');
            return true;
        } catch (error) {
            console.error('保存博客数据失败:', error);
            return false;
        }
    }

    // 更新元素内容
    updateElement(id, value) {
        const element = document.getElementById(id);
        if (element) {
            element.textContent = value;
        }
    }

    // 显示错误信息
    showError(message) {
        commonManager.showError(message);
    }
}

// 初始化博客列表管理器
const blogListManager = new BlogListManager();

// 导出供其他模块使用
window.BlogListManager = BlogListManager;
window.blogListManager = blogListManager;

